﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace S.Organization.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly OrganizationDbContext dbContext;

        public BaseRepository(OrganizationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public async Task<int> CreateAsync(T entity)
        {
            var dbSet = dbContext.Set<T>();
            await dbSet.AddAsync(entity);
            return await dbContext.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(List<T> t)
        {
            var dbSet = dbContext.Set<T>();
            dbSet.RemoveRange(t);
            return await dbContext.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            var dbSet = dbContext.Set<T>().AsNoTracking();
            return await dbSet.ToListAsync();
        }

        public async Task<T> GetAsync(int id)
        {

            return await dbContext.Set<T>().FindAsync(id);
        }

        public async Task<List<T>> SelAllAsync(Expression<Func<T, bool>> expression)
        {
            var dbSet = dbContext.Set<T>().AsNoTracking();
            return await dbSet.Where(expression).ToListAsync();
        }

        public async Task<int> UpdateAsync(T entity)
        {
            dbContext.Update(entity);
            return await dbContext.SaveChangesAsync();
        }


        public async Task<IQueryable<T>> AllAsync()
        {
            var result = await Task.FromResult(dbContext.Set<T>().AsQueryable());
            return result;
        }

        public async Task<int> BatchDeleteAsync(string id)
        {
            DbSet<T> dbset = dbContext.Set<T>();
            var result = dbset.FindAsync(id);
            dbContext.Remove(result);
            return await dbContext.SaveChangesAsync();
        }
 

        public async Task<int> DeleteAllAsync(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset = dbContext.Set<T>();
            var result = dbset.Where(expression);
            dbContext.RemoveRange(result);
            return await dbContext.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            DbSet<T> dbset = dbContext.Set<T>();
            var result = dbset.Find(id);
            dbContext.Remove(result);
            return await dbContext.SaveChangesAsync();
        }

 
 
    }
}
